package cc.aiee.core.kit;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;

import cc.aiee.core.pojo.vo.HttpPrintVO;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpGlobalConfig;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;

public class KitHttp {

	/**
	 * get 请求
	 *
	 * @param url 请求url
	 * @return {@link String} 请求返回的结果
	 */
	public static String get(String url) {
		return HttpUtil.get(url);
	}

	public static String post(String url, Map<String, String> formMap) {
		HttpRequest request = HttpRequest.post(url);
		if (MapUtil.isNotEmpty(formMap)) {
//			formMap.forEach(request::form);
			formMap.forEach((key, value) -> request.form(key, value));
		}
		HttpResponse response = request.timeout(HttpGlobalConfig.getTimeout()).execute();
		return response.body();
	}

	/**
	 * 打印请求报文
	 * 
	 * @deprecated 获取getInputStream()后无法再次获取数据流
	 * @param request
	 * @return
	 * @author YangLong <br>
	 *         2020-09-29 10:00:56
	 */
	public static HttpPrintVO print(HttpServletRequest request) {
		HttpPrintVO print = new HttpPrintVO();
		print.setUrl(request.getRequestURL().toString());
		print.setIp(KitIp.getRealIp(request));
		print.setMethod(request.getMethod());
		print.setProtocol(request.getProtocol());
		print.setPort(request.getServerPort());

		Map<String, String> headers = new HashMap<>();
		Enumeration<String> headerNames = request.getHeaderNames();
		while (headerNames.hasMoreElements()) {
			String headerName = headerNames.nextElement();
			headers.put(headerName, request.getHeader(headerName));
		}

		print.setHeaders(headers);

		Map<String, Object> parameter = new HashMap<>();
		Enumeration<String> parameterNames = request.getParameterNames();
		while (parameterNames.hasMoreElements()) {
			String name = parameterNames.nextElement();
			parameter.put(name, request.getParameter(name));
		}
		print.setParams(parameter);

		boolean isJsonContent_Type = StrUtil.equals("application/json", request.getHeader("Content-Type"), true);

		if (StrUtil.equals("POST", print.getMethod(), true) && isJsonContent_Type) {
			try {
//				BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
//				StringBuilder sb = new StringBuilder();
//				String line = null;
//				while ((line = reader.readLine()) != null) {
//					sb.append(line);
//				}
//				String json = sb.toString();
//				json = JSONObject.toJSONString(json, true);

				JSONObject parseObject = JSONObject.parseObject(request.getInputStream(), JSONObject.class,
						Feature.SortFeidFastMatch);
				print.setBody(parseObject.toString(SerializerFeature.PrettyFormat));
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
//				try {
//					request.getInputStream().close();
//				} catch (IOException e) {
//					e.printStackTrace();
//				}
			}
		}

		return print;
	}

	public static String readDataJson(HttpServletRequest request) {
		try {
			BufferedReader streamReader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
			StringBuilder responseStrBuilder = new StringBuilder();
			String inputStr;
			while ((inputStr = streamReader.readLine()) != null) {
				responseStrBuilder.append(inputStr);
			}
			return responseStrBuilder.toString();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}

	public static String readData(HttpServletRequest request) {
		BufferedReader br = null;
		try {
			StringBuilder result = new StringBuilder();
			br = request.getReader();
			for (String line; (line = br.readLine()) != null;) {
				if (result.length() > 0) {
					result.append("\n");
				}
				result.append(line);
			}
			return result.toString();
		} catch (IOException e) {
			throw new RuntimeException(e);
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
